package com.jay.media.music.ui.base

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.navigation.fragment.NavHostFragment

/**
 * Create by xuzhou4
 * Date 2021/11/15
 */
object BackHandleHelper {

    fun handleBackPress(fragmentManager: FragmentManager): Boolean {
        return handleBackPress(fragmentManager, 0)
    }
    fun handleBackPress(fragmentManager: FragmentManager, maxCount:Int): Boolean {
        val fragments: List<Fragment> = fragmentManager.fragments
        for (i in fragments.indices.reversed()) {
            val child: Fragment = fragments[i]
            if (isFragmentBackHandled(child)) {
                return true
            }
        }
        if (fragmentManager.backStackEntryCount > maxCount) {
            fragmentManager.popBackStack()
            return true
        }
        return false
    }

    fun handleBackPress(fragment: Fragment): Boolean {
        return handleBackPress(fragment.childFragmentManager)
    }

    fun handleBackPress(fragmentActivity: FragmentActivity): Boolean {
        return handleBackPress(fragmentActivity.supportFragmentManager)
    }

    /**
     * 判断Fragment是否处理了Back键
     *
     * @return 如果处理了back键则返回 **true**
     */
    fun isFragmentBackHandled(fragment: Fragment?): Boolean {
        return (fragment != null && fragment.isVisible
                && fragment.userVisibleHint
                && (fragment is FragmentBackHandler
                && (fragment as FragmentBackHandler).onBackPressed()) ||
                (fragment is NavHostFragment && handleBackPress(fragment.childFragmentManager, 2)))
    }
}